package com.zf.shuashua.advert;

import android.app.Activity;
import android.content.Context;

import com.huawei.openalliance.ad.inter.HiAd;
import com.huawei.openalliance.ad.inter.RewardAdLoader;
import com.huawei.openalliance.ad.inter.data.IRewardAd;
import com.huawei.openalliance.ad.inter.listeners.IRewardAdStatusListener;
import com.huawei.openalliance.ad.inter.listeners.RewardAdListener;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.AdvertUtils;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.utils.Util;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;

/**
 * 激励视频展示
 * 华为激励视频
 */
public class RewardAdvertHwManager {

    private RewardAdLoader rewardAdLoader;
    private String mAdvertType = AdvertConstants.REWARD_TYPE_TASK;
    //TODO:测试代码位ID
    //正式：x3e6loub71\测试：e7hm5vx799
    private String mCodeId = "x3e6loub71";
    private String mReportID = "";

    private OnRewardListener mListener;
    private String uuiThirdAdvert;
    private String planId;

    private static RewardAdvertHwManager instance;
    private WeakReference<Activity> weakReference;
    private boolean isComplete = false;

    //预加载的广告
    private IRewardAd rewardAd;

    private RewardAdvertHwManager() {
    }

    public static RewardAdvertHwManager getInstance() {
        if (null == instance) {
            synchronized (RewardAdvertHwManager.class) {
                if (null == instance) {
                    instance = new RewardAdvertHwManager();
                }
            }
        }
        return instance;
    }

    public void showAdvert(Activity activity, String advertType, String reportId, OnRewardListener listener) {
        this.weakReference = new WeakReference<>(activity);
        this.mAdvertType = advertType;
        this.mReportID = reportId;
        this.mListener = listener;
        isComplete = false;
        mCodeId = getCodeId();
        showAd();
    }

    private void showAd(){
        if (rewardAd == null) {
            handleVideoError();
            return;
        }
        //广告展示前判断广告是否过期或是否失效
        if (rewardAd.isExpired() || !rewardAd.isValid()) {
            handleVideoError();
            return;
        }
        uuiThirdAdvert = Util.getUUID32();
        planId = System.identityHashCode(rewardAd) + "";

        rewardAd.setMute(true);
        rewardAd.show(weakReference.get(), new IRewardAdStatusListener() {

            /**
             * 用户达成奖励，开发者可以在该接口中给用户发放奖励，
             * 同一个广告对象只会回调一次
             * */
            @Override
            public void onRewarded() {
                isComplete = true;
            }

            /** 激励广告展示 */
            @Override
            public void onAdShown() {
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoStart, getReportType(), "10");
            }

            /** 激励广告被点击 */
            @Override
            public void onAdClicked() {
                if (mListener != null) {
                    mListener.onAdClick();
                }
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoClick, getReportType(), "10");

            }

            /** 激励广告视频播放结束 */
            @Override
            public void onAdCompleted() {
                isComplete = true;
                if (mListener != null) {
                    mListener.onVideoComplete();
                }
            }

            /**
             * 1、激励广告未播放完成，触发确认弹框，点击关闭按钮触发
             * 2、激励广告播放完成，点击关闭按钮触发
             * 3、激励广告播放完成，虚拟按钮返回不触发，集成自行处理
             * */
            @Override
            public void onAdClosed() {
                dealClose(planId, mListener);
            }

            /** 在广告播放过程中出现异常 */
            @Override
            public void onAdError(int i, int i1) {
                handleVideoError();
                reportRequestFail(i + "", i1 + "");
            }
        });
        //预加载下一个
        loadAd(weakReference.get());
    }

    public void loadAd(Context context) {
        mCodeId = getCodeId();
        HiAd.getInstance(context).enableUserInfo(true); // 设置已同意用户协议标识，前面已经判断是否同意过用户协议，在这里再次调用一下；手机克隆场景，有可能会丢失保存的同意标识。
        // 实例化激励广告加载器，并设置广告位ID，可以支持一次传多个广告位ID
        rewardAdLoader = new RewardAdLoader(context, new String[]{mCodeId});

        // 设置激励监听器
        rewardAdLoader.setListener(new RewardAdListener() {
            /**获取广告成功回调接口*/
            @Override
            public void onAdsLoaded(Map<String, List<IRewardAd>> adMap) {
                if (!checkAdMap(adMap)) {
                    return;
                }
                reportRequestSucc(1);
                cashReward(adMap.get(mCodeId));
            }

            /**获取广告失败回调接口*/
            @Override
            public void onAdFailed(int errorCode) {
                reportRequestFail(errorCode + "", "load ad failed");
            }
        });

        //DeviceType 4:手机 5:平板 6:机顶盒
        rewardAdLoader.loadAds(4, false);

        reportRequestStart();
    }

    private void handleVideoError(){
        weakReference.get().runOnUiThread(() -> {
            if (mListener != null) {
                mListener.onVideoError();
            }
        });
    }

    /**
     * 缓存激励视频广告
     * @param rewardAdList
     */
    private void cashReward(List<IRewardAd> rewardAdList) {
        if (rewardAdList == null || rewardAdList.isEmpty()) {
            return;
        }

        final IRewardAd rewardAd = rewardAdList.get(0);
        if (rewardAd == null) {
            return;
        }
        //广告展示前判断广告是否过期或是否失效
        if (rewardAd.isExpired() || !rewardAd.isValid()) {
            return;
        }
        this.rewardAd = rewardAd;
    }

    private void reportRequestStart(){
        ActionThirdReportManager.getInstance().reportRequestStart(10, 2, mCodeId, 1);
    }

    private void reportRequestSucc(int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(10, 2, mCodeId, return_num);
    }

    private void reportRequestFail(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestFail(10, 2, mCodeId, 1, error_code, error_msg);
    }

    private void reportRequestRend(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestRend(10, 2, mCodeId, error_code, error_msg);
    }

    private void dealClose(String planId, OnRewardListener listener){
        if(!isComplete){
            return;
        }
        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoEnd, getReportType(), "10", new ACallback<BaseData>() {
            @Override
            public void onSuccess(BaseData data) {
                if (data != null && data.isStatus()) {
                    weakReference.get().runOnUiThread(() -> {
                        if (listener != null) {
                            listener.onAdClose();
                        }
                    });
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }

    private boolean checkAdMap(Map adMap) {
        // Activity 销毁，则不展示广告
//        if (isDestroyed() || isFinishing()) {
//            Log.e(TAG, "checkAdMap failed, activity.isDestoryed:" + isDestroyed() + ", activity.isFinishing:" + isFinishing());
//            return false;
//        }

        // 广告列表为空
        if (adMap == null && adMap.isEmpty()) {
            return false;
        }

        return true;
    }

    private String getReportType() {
        return AdvertUtils.getReportType(mAdvertType, mReportID);
    }

    private String getCodeId() {
        return "x3e6loub71";
    }

}
